package com.zookeeper8022.zkclient;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author liyanhao
 * @Date 2023-02-17 18:14
 */
@Slf4j
public class zkClientDemo {
    private static final String CONNECT_STR = "192.168.139.30:2191";
    private final static String CLUSTER_CONNECT_STR =
            "192.168.139.30:2191,192.168.139.30:2192,192.168.139.30:2193";

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper(CLUSTER_CONNECT_STR, 4000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                if (Event.KeeperState.SyncConnected ==
                        watchedEvent.getState() &&
                        watchedEvent.getType() == Event.EventType.None) {
                    //如果收到了服务端的响应事件 链接成功
                    countDownLatch.countDown();
                    System.out.println("建立连接");
                }
            }
        });
        System.out.println("连接中");
        countDownLatch.await();
        //CONNECTED
        System.out.println(zooKeeper.getState());
        //创建持久节点
        /*zooKeeper.create("/user", "zhangsan".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);*/
//        zooKeeper.delete("/user",0);
       //同步创建节点
        String zkNode = zooKeeper.create("/ZK_NODE2", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("create path:"+zkNode);

        //修改节点数据
        Stat stat = new Stat();
        byte[] data = zooKeeper.getData("/ZK_NODE2", false, stat);
        System.out.println("修改前:"+new String(data));
        zooKeeper.setData("/ZK_NODE2", "changed!".getBytes(), stat.getVersion());
        byte[] dataAfer = zooKeeper.getData("/ZK_NODE2", false, stat);
        System.out.println("修改后:"+new String(dataAfer));

    }
}
